package com.hghivln.aspectj;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.hghivln.aspectj.annotation.Log;
import com.hghivln.aspectj.enums.BusinessStatus;
import com.hghivln.pojo.domain.OperLog;
import com.hghivln.pojo.domain.User;
import com.hghivln.service.OperLogService;
import com.hghivln.utils.AddressUtils;
import com.hghivln.utils.IpUtils;
import com.hghivln.utils.ServletUtils;
import com.hghivln.utils.ShiroUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

@Component
@Aspect
@Log4j2
public class OperLogAspect {

    @Autowired
    private OperLogService operLogService;

    /**
     * 声明切入点
     * 只要 Controller 的方法有 @Log 注解就切入
     */
    @Pointcut("@annotation(com.hghivln.aspectj.annotation.Log)")
    public void logPointCut(){}

    /**
     * 后置通知
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()",returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint,Object jsonResult) {
        handleLog(joinPoint,jsonResult,null);
    }

    /**
     * 拦截异常操作
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(value = "logPointCut()",throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint,Exception e) {
        handleLog(joinPoint,null,e);
    }

    /**
     * 是否存在注解，如果存在就获取注解
     */
    private Log getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (ObjectUtils.isNotEmpty(method)) {
            return method.getAnnotation(Log.class);
        }
        return null;
    }

    /**
     * 获取注解的详细信息（对方法的描述信息 用于Controller层注解）
     */
    private void getControllerMethodDescription(JoinPoint joinPoint, Log controllerLog, OperLog operLog) {
        // 设置 action 动作
        operLog.setBusinessType(String.valueOf(controllerLog.businessType().ordinal()));
        // 设置标题
        operLog.setTitle(controllerLog.title());
        // 设置操作人类别
        operLog.setOperatorType(controllerLog.operatorType().ordinal());
        // 是否需要保存 request，参数和值
        if (controllerLog.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中
            setRequestValue(joinPoint,operLog);
        }
    }

    /**
     * 获取请求的参数，放入 log 中
     */
    public void setRequestValue(JoinPoint joinPoint,OperLog operLog) {
        String requestMethod = operLog.getRequestMethod();
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod))
        {
            String params = argsArrayToString(joinPoint.getArgs());
            operLog.setOperParam(StringUtils.substring(params, 0, 2000));
        }
        else
        {
            Map<?, ?> paramsMap = (Map<?, ?>) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            operLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
        }
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        StringBuilder params = new StringBuilder();
        if (paramsArray != null && paramsArray.length > 0)
        {
            for (int i = 0; i < paramsArray.length; i++)
            {
                if (!isFilterObject(paramsArray[i]))
                {
                    Object jsonObj = JSON.toJSON(paramsArray[i]);
                    params.append(jsonObj.toString()).append(" ");
                }
            }
        }
        return params.toString().trim();
    }
    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    public boolean isFilterObject(final Object o)
    {
        return o instanceof MultipartFile || o instanceof HttpServletRequest
                || o instanceof HttpServletResponse;
    }
    
    public void handleLog(JoinPoint joinPoint,Object jsonResult,Exception e) {

        try {
            // 获得注解
            Log controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null) {
                return;
            }
            // 数据库日志
            OperLog operLog = new OperLog();
            // 操作状态
            operLog.setStatus(String.valueOf(BusinessStatus.SUCCESS.ordinal()));
            // 请求地址
            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
            operLog.setOperIp(ip);
            // 操作地点
            String address = AddressUtils.getRealAddressByIP(ip);
            operLog.setOperLocation(address);
            // 方法返回值
            operLog.setJsonResult(JSON.toJSONString(jsonResult));
            // 请求 URL
            operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
            // 获取当前的用户
            User loginUser = ShiroUtils.getCurrentUser();
            if (ObjectUtils.isNotEmpty(loginUser)) {
                // 操作人员
                operLog.setOperName(loginUser.getUserName());
            }

            if (e != null) {
                // 操作状态
                operLog.setStatus(String.valueOf(BusinessStatus.FAIL.ordinal()));
                // 错误消息
                operLog.setErrorMsg(StringUtils.substring(e.getMessage(),0));
            }

            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");
            // 设置请求方式
            operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
            // 设置注解上的参数
            getControllerMethodDescription(joinPoint,controllerLog,operLog);
            // 设置操作时间
            operLog.setOperTime(DateUtil.date());
            // 保存数据
            operLogService.insertOperLog(operLog);
        } catch (Exception exception) {
            // 记录本地异常日志
            log.error("==异常通知==");
            log.error("异常信息:{}",exception.getMessage());
            exception.printStackTrace();
        }
    }

}
